package com.andnnl.stream;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.*;
import java.util.Map.Entry;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import static java.lang.System.out;


/**
 * cat /home/admin/logs/*.log | grep "Login" | sort | uniq -c | sort -nr
 * Created by chenss on 2020/3/6.
 */
public class LoginCount {
    public static void main(String[] args) throws IOException {
        out.println(" ".getBytes()[0]);//32
        out.println("a".getBytes()[0]);//97
        out.println("n".getBytes()[0]);//97

        String lhs = "299 Mon, Login, Royal Fellhauer";
        String rhs = "299 Mon, Login, Roy Soros";

        String lhs2 = "299 Mon, Login, Royal Fellhauer";
        String rhs2 = "299 Mon, Login, Royb Soros";

        out.println(lhs.compareTo(rhs));
        out.println(compareTo(lhs,rhs));
        out.println(lhs2.compareTo(rhs2));
        out.println(compareTo(lhs2,rhs2));
//        out.println(lhs.getBytes().);

        out.println("start...");
        long t1 = System.currentTimeMillis();
//        test();
//        test2();
        long t2 = System.currentTimeMillis();
        out.println("use time:" + (t2 - t1));
    }

    private static void test2() throws IOException {
//        Path path = Paths.get("D:\\IdeaProjects\\file-scanner\\logs");
        Path path = Paths.get("D:\\IdeaProjects\\testjava8\\src\\main\\java\\com\\andnnl\\stream");
        Stream<Path> files = Files.list(path).filter(f -> f.getFileName().toString().endsWith("log"));
        Map<String, Long> rsMap = new HashMap<>();
        files.parallel().forEach(p -> {
            try {
                Map<String, Long> map = Files.lines(p).filter(s -> s.contains("Login"))
                        .collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));
                map.forEach((k, v) -> rsMap.merge(k, v, Long::sum));
            } catch (IOException e) {
                e.printStackTrace();
            }
        });
//        rsMap.entrySet().stream().sorted(Entry.<String, Long>comparingByValue().reversed())
//                .forEach(a -> out.println(a.getValue() + " " + a.getKey()));

        //先排序Long，再排String
//        List<String> list = rsMap.entrySet().stream().sorted(
//                Comparator.comparing(Map.Entry<String, Long>::getValue)
//                        .thenComparing(Map.Entry<String, Long>::getKey).reversed())
//                .map(a -> a.getValue() + " " + a.getKey())
//                .collect(Collectors.toList());

        //先排序Long，再排String
        List<String> list = rsMap.entrySet().stream().sorted((lhs, rhs) -> {
                    if (lhs.getValue() == rhs.getValue()) {
//                        return -lhs.getKey().compareTo(rhs.getKey());//倒序
                        return -lhs.getKey().replaceAll(" ","").compareTo(rhs.getKey().replaceAll(" ",""));//删除空格，倒序
//                        return -(compareTo(lhs.getKey(),rhs.getKey()));//模拟shell的sort
                    } else {
                        return -Long.compare(lhs.getValue(), rhs.getValue());//倒序
                    }
                }
        )
                .map(a -> a.getValue() + " " + a.getKey())
                .collect(Collectors.toList());

        /*Map<Long, List<Entry<String, Long>>> a =
                rsMap.entrySet().stream().collect(Collectors.groupingBy((entry) -> entry.getValue(), Collectors.toList()));



        Map<Long, List<String>> rs = rsMap.entrySet().stream().collect(Collectors.toMap((entry) -> entry.getValue(),
                p -> {
                    List<String> getNameList = new ArrayList<>();
                    getNameList.add(p.getKey());
                    return getNameList;
                },
                (List<String> value1, List<String> value2) -> {
                    value1.addAll(value2);
                    return value1;
                }
        ));
        List<String> list = new ArrayList<>();
        rs.entrySet().stream().sorted(Entry.<Long, List<String>>comparingByKey().reversed())
                .forEach(e -> {
                    Long key = e.getKey();
                    List<String> l = e.getValue();
                    Collections.sort(l);
                    l.sort(Comparator.reverseOrder()); //倒序
                    out.println(key + "->" + l);

                    l.forEach(s -> list.add(key + " " + s));
//
                });*/
        list.forEach(out::println);

    }
    public static int compareTo(String str,String anotherString) {
        char v1[] = str.toCharArray();
        char v2[] = anotherString.toCharArray();
        int len1 = v1.length;
        int len2 =v2.length;
        int lim = Math.min(len1, len2);
        int k = 0;
        while (k < lim) {
            char c1 = v1[k];
            char c2 = v2[k];
            if (c1 != c2) {
                if(c1==32 && c2==109){return -1;}
                if(c2==32){return -1;}
                return c1 - c2;
            }
            k++;
        }
        return len1 - len2;
    }

    private static void test() throws IOException {
        Stream<String> lines = Files.lines(Paths.get("D:\\IdeaProjects\\testjava8\\src\\main\\java\\com\\andnnl\\stream\\data.txt"));

        Map<String, Long> map = lines.filter(s -> s.contains("Login"))
                .collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));
        map.entrySet().stream().sorted(Entry.<String, Long>comparingByValue().reversed())
                .forEach(a -> out.println(a.getValue() + " " + a.getKey()));
    }


}
